package com.sneakxy.mybase4j.platform.controller;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sneakxy.mybase4j.base.bean.ValidAdd;
import com.sneakxy.mybase4j.base.bean.ValidEdit;
import com.sneakxy.mybase4j.base.controller.BaseController;
import com.sneakxy.mybase4j.platform.beans.Launcher;
import com.sneakxy.mybase4j.platform.service.ILauncherService;
import com.sneakxy.mybase4j.platform.service.ILauncherSettingService;
import com.sneakxy.mybase4j.util.BeanHelper;
import com.sneakxy.mybase4j.util.DataGrid;
import com.sneakxy.mybase4j.util.PageSearch;
import com.sneakxy.mybase4j.util.Response;

/**
 * 自启动管理
 * @author 潜行的青衣
 * @see
 */
@RestController
@RequestMapping("/api/launcher/")
public class LauncherController extends BaseController {

	@Resource
	private ILauncherService launcherService;
	
	@Resource
	private ILauncherSettingService launcherSettingService;
	
	@RequiresPermissions("sys:launcher:manager")
	@RequestMapping("datagrid")
	public DataGrid<Launcher> datagrid(PageSearch search) {
		if(StringUtils.isBlank(search.getSortName())) {
			search.setSortName("createtime");
		}
		return new DataGrid<Launcher>(launcherService.findBySearch(search.getSearchText(), search.toPageable()));
	}
	
	@RequiresPermissions("sys:launcher:manager:add")
	@RequestMapping("add")
	public Response add(@Validated(ValidAdd.class) Launcher launcher, BindingResult result) {
		if(result.hasErrors()) {
			return this.getFieldErrorsResponse(result);
		}
		
		//去空格
		BeanHelper.trimToNull(launcher);
		
		launcher = this.launcherService.save(launcher);
		return new Response(true, launcher);
	}
	
	@RequiresPermissions("sys:launcher:manager:edit")
	@RequestMapping("edit")
	public Response edit(@Validated(ValidEdit.class) Launcher launcher, BindingResult result) {
		if(result.hasErrors()) {
			return this.getFieldErrorsResponse(result);
		}
		
		//去空格
		BeanHelper.trimToNull(launcher);
		
		Launcher old = this.launcherService.findOne(launcher.getId());
		launcher.setCreatetime(old.getCreatetime());
		
		launcher = this.launcherService.save(launcher);
		//如果不可以用户手动控制
		if(!launcher.isManual()) {
			//必须开启
			this.launcherSettingService.deleteByLid(launcher.getId());
		}
		return new Response(true, launcher);
	}
	
	@RequiresPermissions("sys:launcher:manager:remove")
	@RequestMapping("remove")
	public Response remove(String[] ids) {
		if(ids != null) {
			for(String id:ids) {
				this.launcherSettingService.deleteByLid(id);
				this.launcherService.delete(id);
			}
		}
		return new Response(true);
	}
	
}
